import { HLogger, Logger } from "./../logger/index";
import { CallHandler, ExecutionContext, NestInterceptor } from "@nestjs/common";
import * as moment from "moment";
import { Observable, tap } from "rxjs";
import { parseId } from "../utils";
import { Request, Response } from "express";

export class HLoggerInterceptor implements NestInterceptor {
  private logger = new KwLogger();
  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
    const ctx = context.switchToHttp();
    const request = ctx.getRequest<Request>();
    const oid = parseId().toString();
    const params = Object.assign({}, request.params, request.body, request.query);
    const url = request.url;
    const method = request.method;
    const now = Date.now();

    const response = ctx.getResponse<Response>();
    const code = response.statusCode;
    return next
      .handle()
      .pipe(
        tap((data) => {
          const cost = Date.now() - now;
          const loggerObj: Logger = {
              oid,
              datetime: moment(now).format('YYYY-MM-DD HH:mm:ss'),
              method,
              url,
              status: code,
              cost,
              params,
              response: data
          }
          this.logger.log(loggerObj);
        })
      )
  }
}